<template>
  <view class="container">
    <view class="form">
      <view class="logo">
        <image src="../../static/logo.png" mode=""></image>
      </view>
      <view class="input-info">
        <view class="info">
          <hedgeFund-Input
            type="text"
            maxlength="10"
            class="input"
            placeholder="请输入机构名称"
            v-model="hedgeFundId"
          />
        </view>
        <view class="info">
          <multiple-picker
            ref="fundInput"
            class="Input"
            placeholder="请选择基金"
            v-model="selectedFunds"
            :columns="fundList"
          />
        </view>
        <!-- <view class="info">
          <view class="subject"
            >建议上传合格投资者证明材料发送私募管理人，以便快速完成数据授权审核</view
          >
          <uni-file-picker
            title=" "
            :auto-upload="false"
            v-model="fileList"
            file-mediatype="image"
            mode="grid"
            file-extname="png,jpg"
            :limit="6"
            @select="selectUpload"
          />
        </view> -->
        <view class="info">
          <view class="subject"
            >建议上传合格投资者证明材料发送私募管理人，以便快速完成数据授权审核</view
          >
          <view class="media-container">
            <jade-image-upload
              :list="imageList"
              :control="control"
              :maxCount="maxCount"
              :compressSize="compressSize"
              :compressQuality="compressQuality"
              :compressWidth="compressWidth"
              :imageSize="imageSize"
              :sourceType="sourceType"
              @chooseFile="chooseFile"
              @imgDelete="mediaDelete"
            >
            </jade-image-upload>
            <!-- 数据变化的JSON  -->
            <view
              style="
                padding: 20rpx;
                box-sizing: border-box;
                display: flex;
                flex-direction: column;
              "
            >
              图片上传：
              <view style="padding: 20rpx; word-break: break-all">{{
                imageList.length ? JSON.stringify(imageList) : "暂无数据"
              }}</view>
            </view>
          </view>
        </view>
      </view>
      <view class="btn-info">
        <button type="primary" @click="onApprove">权限申请</button>
      </view>
    </view>
  </view>
</template>

<script>
import { getFunds, approve } from "../../apis/api";
import { isLogin } from "../../utils/permission";
export default {
  data() {
    return {
      sourceType: ["album", "camera"],
      // fundList: [],
      // 表单
      hedgeFundId: "",
      selectedFunds: "",

      fileList: [],

      control: true, //是否显示上传控件
      maxCount: 6, //上传最大数量
      compressSize: 5, //照片超出压缩大小 MB
      imageSize: 20, //照片限制大小 MB
      compressQuality: 0.99, //照片压缩质量
      compressWidth: 750, //照片压缩宽度
      uploadTask: null,
      imageList: [], //数据源
    };
  },
  onLoad() {
    // //先写业务代码？
    // if (!isLogin(true)) {
    //   return;
    // }
  },
  onShow: function () {
    wx.hideHomeButton();
  },
  methods: {
    validate() {
      if (!this.hedgeFundId) {
        return Promise.reject({ message: "请输入机构名称" });
      }
      if (!this.selectedFunds || this.selectedFunds.length == 0) {
        return Promise.reject({ message: "请选择要授权的基金" });
      }
      return Promise.resolve();
    },
    clearInput() {
      this.hedgeFundId = [];
      this.selectedFunds = [];
    },
    getFundList() {
      this.selectedFunds = [];
      if (this.hedgeFundId) {
        var para = {
          hedgeFundId: this.hedgeFundId,
        };
        getFunds(para)
          .then((res) => {
            let list = [];
            res.data.data.forEach((e) => {
              list.push({
                key: e.fundId,
                label: `[${e.level}]${e.name}`,
                desc: e.name,
              });
            });
            this.fundList = list;
          })
          .catch((err) => {
            console.log("err", err);
          });
      }
    },
    onApprove() {
      let that = this;
      this.validate()
        .then(() => {
          let name = this.$refs.fundInput.getSelectDesc();
          wx.showModal({
            title: "提示",
            content: `确定申请基金[${name}]授权？`,
            success(res) {
              if (res.confirm) {
                uni.showLoading({
                  title: "申请中...",
                });

                let para = {
                  fundIds: that.selectedFunds.map((f) => {
                    return f.fundId;
                  }),
                };

                approve(para)
                  .then((res) => {
                    let result = res.data.result;
                    if (result.status === 1) {
                      uni.hideLoading();
                      uni.showModal({
                        content: "权限申请已经发出",
                        showCancel: false,
                      });
                      that.clearInput();
                    } else {
                      return Promise.reject({ message: result.message });
                    }
                  })
                  .catch((err) => {
                    uni.hideLoading();
                    uni.showModal({
                      content: err.message,
                      showCancel: false,
                    });
                  });
              }
            },
          });
        })
        .catch((err) => {
          uni.showToast({
            title: err.message,
            icon: "none",
          });
        });
    },

    selectUpload(e) {
      e.tempFilePaths.forEach((path) => {
        uni.uploadFile({
          url: "url", //仅为示例，非真实的接口地址
          filePath: e.tempFilePaths[0],
          name: "file",
          // formData: {
          // 	'file': ''
          // },
          success: (uploadFileRes) => {
            console.log(uploadFileRes.data);
          },
          fail: (err) => {
            console.log(err);
          },
        });
      });
    },

    //上传
    chooseFile(e) {
      this.uploadFileToServe(e);
    },
    //中断上传并删除
    mediaDelete(e) {
      this.uploadTask ? this.uploadTask.abort() : "";
      this.imageList.splice(e, 1);
    },
    //上传逻辑处理
    uploadFileToServe(urlList) {
      if (!urlList || urlList.length <= 0) {
        return;
      }
      //以七牛云为例,可根据实际需求灵活调整
      uni.request({
        url: "qiniu", //后端接口，仅为示例，并非真实接口地址。
        method: "GET",
        success: (res) => {
          let token = res.data.data; //拿到上传七牛所必须的token
          urlList.forEach((item) => {
            this.uploadTask = uni.uploadFile({
              url: "qiniu", //七牛上传接口，仅为示例
              filePath: item.src,
              name: "file",
              formData: {
                token: token,
              },
              success: (res) => {
                let data = JSON.parse(res.data); //七牛返回的数据
                if (!data.data.url) {
                  item.status = "error";
                  item.progress = "上传失败";
                } else {
                  item.status = "success";
                  item.progress = "上传成功";
                  item.src = data.data.url;
                }
              },
            });
            this.uploadTask.onProgressUpdate((res) => {
              item.percent = res.progress;
              this.imageList.splice(item.index, 1, item);
            });
          });
        },
      });
    },
  },
  watch: {
    hedgeFundId: {
      handler(newValue, oldValue) {
        this.getFundList();
      },
    },
  },
};
</script>

<style lang="scss">
@import "approve.scss";
</style>
